<template>
  <div class="cart-container">
    <Header/>
    <div class="cart-content">
      <div class="cart-title">
        <h2>我的购物车</h2>
        <span class="course-count">共{{ cartCourses.length }}门课程</span>
      </div>

      <div class="cart-table">
        <div class="table-header">
          <div class="checkbox-col">
            <input type="checkbox" v-model="selectAll" @change="handleSelectAll">
            全选
          </div>
          <div class="course-col">课程</div>
          <div class="validity-col">有效期</div>
          <div class="price-col">单价</div>
          <div class="operation-col">操作</div>
        </div>

        <div class="table-body">
          <div v-for="(course, index) in cartCourses" :key="index" class="table-row">
            <div class="checkbox-col" >
              <input type="checkbox" v-model="course.selected" @change="toggleCourse(index)">
            </div>
            <div class="course-col">
              <img :src="course.image" :alt="course.title">
              <span class="course-title">{{ course.id }}--{{ course.title }}</span>
            </div>
            <div class="validity-col">
              <select v-model="course.validity" @change="updateCoursePrice(course,course.validity)">
                <option v-for="option in course.expireOptions" :value="option.value"
                        :key="option.value">{{option.label}}</option>
              </select>
            </div>
            <div class="price-col">¥{{ course.price }}</div>
            <div class="operation-col">
              <button @click="removeCourse(index)" class="delete-btn">删除</button>
            </div>
          </div>
        </div>
      </div>

      <div class="cart-footer">
        <div class="left-operations">
          <button class="inverse-select" @click="inverseSelect">反选</button>
          <button class="batch-delete" @click="batchDelete">批量删除</button>
        </div>
        <div class="right-summary">
          <span class="total-label">合计：</span>
          <span class="total-price">¥{{ totalPrice }}</span>
          <button class="checkout-btn" @click="handleCheckout">去结算 ({{ selectedCount }})</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import Header from '../components/Header.vue'
import { watch } from 'vue'

const router = useRouter()
const selectAll = ref(false)
const cartCourses = ref([])
const courseExpireInfo = ref({})



// 刷新token
const refreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token')
    if (!refreshToken) {
      throw new Error('No refresh token')
    }

    const response = await axios.post('http://127.0.0.1:8000/refresh/', {
      refresh: refreshToken
    })

    if (response.data.access) {
      // 更新access token
      const newToken = response.data.access
      localStorage.setItem('token', newToken)
      sessionStorage.setItem('token', newToken)
      return newToken
    }
    throw new Error('Failed to refresh token')
  } catch (error) {
    console.error('刷新token失败:', error)
    throw error
  }
}

// 获取购物车数据
const fetchCartData = async (token) => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/api/carts_list/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.status === 200 && response.data.code === 1) {
      // 转换后端数据格式为前端所需格式
      cartCourses.value = response.data.data.carts_list.map(item => ({
        id: item.id,
        title: item.name,
        image: item.course_img,
        price: item.price,
        validity: 'forever',
        selected: item.is_selected === 1,
        expireOptions: [] // 初始化有效期选项
      }))

      const courseIds = cartCourses.value.map(course => course.id)
      await fetchCourseEporeInfo(courseIds)


    } else {
      ElMessage.error(response.data.message || '获取购物车数据失败')
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      try {
        // 尝试刷新token
        const newToken = await refreshToken()
        // 使用新token重试请求
        return fetchCartData(newToken)
      } catch (refreshError) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')
        await router.push('/login')
      }
    } else {
      ElMessage.error('获取购物车数据失败')
    }
  }
}

// 初始化购物车数据
const initCart = async () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    await router.push('/login')
    return
  }
  await fetchCartData(token)
}

// 计算属性
const selectedCount = computed(() => {
  return cartCourses.value.filter(course => course.selected).length
})

const totalPrice = computed(() => {
  return cartCourses.value
      .filter(course => course.selected)
      .reduce((sum, course) => sum + course.price, 0)
      .toFixed(2)
})

// 删除购物车商品
const deleteCartItems = async (courseIds) => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    await router.push('/login')
    return
  }

  try {
    const response = await axios.post('http://127.0.0.1:8000/api/carts_delete/', {
      course_ids: courseIds
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.status === 200) {
      if (response.data.code === 1) {
        ElMessage.success(response.data.message || '删除成功')
        // 重新获取购物车数据
        await fetchCartData(token)
      } else if (response.data.code === 0) {
        ElMessage.error(response.data.message || '删除失败')
      }
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      try {
        // 尝试刷新token
        const newToken = await refreshToken()
        // 使用新token重试请求
        return deleteCartItems(courseIds)
      } catch (refreshError) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')
        await router.push('/login')
      }
    } else {
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 删除单个商品
const removeCourse = async (index) => {
  const courseId = cartCourses.value[index].id

  console.log(courseId)
  console.log(typeof courseId)
  //把string类型转化成int
  const course_id = parseInt(courseId)
  console.log(course_id)
  console.log(typeof course_id)
  await deleteCartItems(course_id)
}

// 批量删除选中的商品
const batchDelete = async () => {
  const selectedCourseIds = cartCourses.value
      .filter(course => course.selected)
      .map(course => course.id)

  if (selectedCourseIds.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }

  await deleteCartItems(selectedCourseIds)
}


// 全选/取消全选
const handleSelectAll = async () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    await router.push('/login')
    return
  }

  try {
    const response = await axios.post('http://127.0.0.1:8000/api/carts_selected/', {
      is_selected: selectAll.value ? 1 : 0
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.status === 200) {
      if (response.data.code === 1) {
        ElMessage.success(response.data.message)
        // 重新获取购物车数据
        await fetchCartData(token)
      } else {
        ElMessage.error(response.data.message || '操作失败')
        // 操作失败时恢复选中状态
        selectAll.value = !selectAll.value
      }
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      try {
        // 尝试刷新token
        const newToken = await refreshToken()
        // 使用新token重试请求
        return handleSelectAll()
      } catch (refreshError) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')
        await router.push('/login')
      }
    } else {
      ElMessage.error('操作失败，请稍后重试')
      // 操作失败时恢复选中状态
      selectAll.value = !selectAll.value
    }
  }
}

// 监听全选状态变化
watch(cartCourses, () => {
  // 当所有商品都被选中时，自动设置全选状态为true
  selectAll.value = cartCourses.value.length > 0 && cartCourses.value.every(course => course.selected)
}, { deep: true })


const inverseSelect = async()=>{
  const courseIds =  cartCourses.value.map(course=>course.id)
  if(courseIds.length===0){
    ElMessage.warning('请选择要操作的课程')
    return
  }
  await toggleCartItems(courseIds)
}

const toggleCourse = async (index) => {
  const courseId = cartCourses.value[index].id
  const course_ids = parseInt(courseId)
  await toggleCartItems(course_ids)
}

// 反选商品
const toggleCartItems = async (courseIds) => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    await router.push('/login')
    return
  }

  try {
    const response = await axios.post('http://127.0.0.1:8000/api/carts_no/', {
      course_ids: courseIds
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.status === 200) {
      if (response.data.code === 1) {
        ElMessage.success(response.data.message)
        await fetchCartData(token)
        // 更新本地商品选中状态
        if (response.data.data && response.data.data.updated_course) {
          response.data.data.updated_course.forEach(item => {
            const course = cartCourses.value.find(c => c.id === item.course_id)
            if (course) {
              course.selected = item.is_selected === 1
            }
          })
        }
      } else {
        ElMessage.error(response.data.message || '操作失败')
      }
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      try {
        // 尝试刷新token
        const newToken = await refreshToken()
        // 使用新token重试请求
        return toggleCartItems(courseIds)
      } catch (refreshError) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')
        await router.push('/login')
      }
    } else {
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}


//有效期
const updateCoursePrice=(course,validity)=>{
  const expireOption = course.expireOptions.find(option => option.value === Number(validity))
  if (expireOption) {
    course.price = expireOption.price
  }
}

const fetchCourseEporeInfo = async (courseIds) => {
  console.log(courseIds)
  console.log(courseIds.join(','))
  try {
    const res = await axios.get("http://127.0.0.1:8000/api/expire/?course_ids=" + courseIds.join(','))
    console.log(res.data.code)
    if (res.data.code === 1) {
      courseExpireInfo.value = res.data.data
      console.log(courseExpireInfo.value)
      console.log(cartCourses.value)
      // 更新购物车中的课程有效期选项和价格
      cartCourses.value = cartCourses.value.map(course => {
        console.log(course)
        const expireInfo = courseExpireInfo.value[course.id]
        console.log(expireInfo)
        if (expireInfo) {
          return {
            ...course,
            expireOptions: expireInfo.expire_list.map(item => ({
              value: item.expire_time,
              label: item.expire_text,
              price: item.price
            })),
            // 默认选择第一个有效期选项
            validity: expireInfo.expire_list[0].expire_time,
            price: expireInfo.expire_list[0].price

          }

        }
        return course
      })


    }
  } catch (error) {

  }
}


//结算跳转
function handleCheckout(){
  const selectedCourses = cartCourses.value.filter(course => course.selected)
  console.log(selectedCourses)
  if (selectedCourses.length === 0) {
    ElMessage.warning('请选择要结算的课程')
    return
  }

  const checkoutInfo = selectedCourses.map(course => ({
        courseId: course.id,
        validityId: course.validity,
        price: course.price,
        validityText: course.expireOptions.find(opt => opt.value === course.validity)?.label||'永久有效'

      })
  )

  router.push({path: '/checkout', query: {courses: JSON.stringify(checkoutInfo)}})
}









// 监听全选状态变化
watch(cartCourses, () => {
  // 当所有商品都被选中时，自动设置全选状态为true
  selectAll.value = cartCourses.value.length > 0 && cartCourses.value.every(course => course.selected)
}, { deep: true })


// 组件挂载时获取购物车数据
onMounted(() => {
  initCart()
})
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.cart-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.cart-title h2 {
  font-size: 24px;
  margin-right: 10px;
}

.course-count {
  color: #666;
}

.cart-table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: grid;
  grid-template-columns: 100px 1fr 200px 150px 100px;
  padding: 15px;
  background: #f7f7f7;
  border-bottom: 1px solid #e8e8e8;
}

.table-row {
  display: grid;
  grid-template-columns: 100px 1fr 200px 150px 100px;
  padding: 15px;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
}

.course-col {
  display: flex;
  align-items: center;
}

.course-col img {
  width: 120px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.course-title {
  font-size: 16px;
  color: #333;
}

select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 120px;
}

.price-col {
  color: #ff6b00;
  font-weight: bold;
}

.delete-btn {
  color: #666;
  background: none;
  border: none;
  cursor: pointer;
}

.delete-btn:hover {
  color: #ff4d4f;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  margin-top: 20px;
  border-radius: 4px;
}

.left-operations button {
  margin-right: 15px;
  padding: 8px 15px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.total-label {
  margin-right: 10px;
}

.total-price {
  color: #ff6b00;
  font-size: 20px;
  font-weight: bold;
  margin-right: 20px;
}

.checkout-btn {
  padding: 10px 30px;
  background: #ff6b00;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.checkout-btn:hover {
  background: #ff7b00;
}
</style>
